package org.edu.modules.oa.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.oa.entity.*;
import org.edu.modules.oa.mapper.IVeOaDiaryMapper;
import org.edu.modules.oa.mapper.IVeUserMapper;
import org.edu.modules.oa.service.IVeOaDiaryService;
import org.edu.modules.oa.service.IVeOaMeetPlaceService;
import org.edu.modules.oa.util.OssDownloadUtil;
import org.edu.modules.oa.vo.VeOaCarInfoExportVo;
import org.edu.modules.oa.vo.VeOaCarJiayouExportVo;
import org.edu.modules.oa.vo.VeOaCarJiayouTableVo;
import org.edu.modules.oa.vo.VeOaDiaryTableVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.midi.Soundbank;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags="工作日记")
@RestController
@RequestMapping("oa/VeOaDiary")
@Slf4j
public class VeOaDiaryController {
    @Resource
    private IVeOaDiaryService iVeOaDiaryService;

    // 日志注解
    @AutoLog(value = "工作日记-显示表格")
    @ApiOperation(value="显示表格", notes="工作日记-显示表格")
    // 显示表格
    @PostMapping(value = "/showTable")

    public Result<?> showTable(VeOaDiaryEntity veOaDiaryEntity,String themeList, Integer startPage, Integer pageSize) {
        if(themeList.equals("")){
            themeList=null;
        }
        if(veOaDiaryEntity.getCreateBy().equals("")){
            veOaDiaryEntity.setCreateBy(null);
        }
        if(veOaDiaryEntity.getRijiType().equals("")){
            veOaDiaryEntity.setRijiType(null);
        }
        HashMap<String, Object> map=iVeOaDiaryService.showVoTable(themeList,veOaDiaryEntity,startPage,pageSize);
        return Result.OK(map);
    }
    @PostMapping("/loadTheme")
    @AutoLog(value = "工作日记-加载主题")
    @ApiOperation(value="显示日记主题", notes="工作日记-加载主题")
    public Result<?> loadTheme(VeOaDiaryEntity veOaDiaryEntity, Integer startPage, Integer pageSize){
        HashMap<String, Object> map=iVeOaDiaryService.selectTheme(veOaDiaryEntity,startPage,pageSize);
        return Result.OK(map);
    }

    @PostMapping("/loadType")
    @AutoLog(value = "工作日记-加载类型")
    @ApiOperation(value="添加日记", notes="工作日记-加载类型")
    public Result<?> loadType(){
        List<VeOaDiaryEntity> typeList=iVeOaDiaryService.selectType();
        return Result.OK(typeList);
    }
    @PostMapping("/submitDary")
    @AutoLog(value = "工作日记-添加日记")
    @ApiOperation(value="添加日记", notes="工作日记-添加日记")
    public Result<?> addWorkDiary(VeOaDiaryEntity veOaDiaryEntity){
        Integer result=iVeOaDiaryService.addDiary(veOaDiaryEntity);
        return Result.OK(result);
    }
    @PostMapping("/allDelete")
    @AutoLog(value = "工作日记-日记删除")
    @ApiOperation(value="工作日记", notes="工作日记-批量删除")
    public Result<?> deleteAllWorkDiary(String idStr){
        Integer result=0;
        String data[] = idStr.split(",");

        for (int i=1;i<data.length;i++){

            result+=iVeOaDiaryService.deleteWorkDiary(Integer.valueOf(data[i]));

        }
        if(result == 0){
            return Result.error(500,"删除失败了");
        }
        return Result.OK();
    }

    @PostMapping("/oneDelete")
    @AutoLog(value = "工作日记-日记删除")
    @ApiOperation(value="工作日记", notes="工作日记-单个删除")
    public Result<?> deleteWorkDiary(Integer id){
        int result=iVeOaDiaryService.deleteWorkDiary(id);

        if(result == 0){
            return Result.error(500,"删除失败了");
        }
        return Result.OK();
    }

    @PostMapping("/editDary")
    @AutoLog(value = "工作日记-日记修改")
    @ApiOperation(value="工作日记", notes="工作日记-日记修改")
    public Result<?> editWorkDiary(VeOaDiaryEntity veOaDiaryEntity){
        int result=iVeOaDiaryService.editWorkDiary(veOaDiaryEntity);

        if(result == 0){
            return Result.error(500,"修改失败了");
        }
        return Result.OK();
    }
    @Resource
    private IVeUserMapper iVeUserMapper;
    //导入
    @AutoLog(value = "工作日记-导入excel表格")
    @ApiOperation(value = "导入excel表格", notes = "工作日记—导入excel表格")
    @PostMapping(value = "importModel")

    public Result<?> excelImport(HttpServletRequest req, HttpServletResponse resp) {
        // 获取文件
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                // 把excel表格的数据存在集合里面去
                List<VeOaDiaryTableVo> list = ExcelImportUtil.importExcel(file.getInputStream(), VeOaDiaryTableVo.class, params);
                // 获取redis存的用户值
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

                // 插入数据的集合
                List<VeOaDiaryEntity> entityList =new ArrayList<>();
                int count =list.size();
                for (VeOaDiaryTableVo vo:list){
                    if(vo.getRijiContent()==null||vo.getTitleStr().equals("")){
                        count--;
                        continue;
                    }
                    VeOaDiaryEntity infoEntity =new VeOaDiaryEntity();
                    infoEntity.setCreateBy(user.getId());
                    infoEntity.setId(vo.getId());
                    infoEntity.setIsDeleted(0);
                    infoEntity.setRijiContent(vo.getRijiContent());
                    infoEntity.setRijiType(vo.getRijiType());
                    infoEntity.setTerminalId(0);
                    infoEntity.setTitleStr(vo.getTitleStr());
                    entityList.add(infoEntity);
                }
                iVeOaDiaryService.saveBatch(entityList);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
//                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + count);
            } catch (Exception e) {
                e.printStackTrace();
//                log.error(e.getMessage(), e);
//                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
//        return super.importExcel(req, resp, VeOaCarJiayouEntity.class);
    }
    //导出
    @AutoLog(value = "工作日记-excel表格")
    @ApiOperation(value = "工作日记导出excel表格", notes = "工作日记—导出excel表格")
    @GetMapping(value = "/exportTable")
    // ModelAndView 导出表格流
    public ModelAndView exportTable() {
        VeOaCarJiayouTableVo veOaCarJiayouTableVo =new VeOaCarJiayouTableVo();
        // 创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 查数据获得加油表格的集合
        List<VeOaDiaryTableVo> list = iVeOaDiaryService.showExcel();

        // 文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME, "工作日记记录");
        // 数据的类型
        mv.addObject(NormalExcelConstants.CLASS, VeOaDiaryTableVo.class);
        // 获取redis存的用户值

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("工作日记记录", "导出人:" + user.getRealname(), "导出工作日记记录");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);


        return mv;
    }

    @AutoLog(value = "工作日记-模板地址获取")
    @ApiOperation(value = "模板地址", notes = "工作日记-模板地址获取")
    @PostMapping(value = "/getUrl")
    public Result<T> getUrl() throws Exception {
        Result result = new Result();
        String url= OssDownloadUtil.getOssDownloadUtil().downFileFromOSS("工作日记导入模板.xls");
        result.success(url);
        return result;
    }
}
